//
//  SearchListViewController.m
//  huashiedu
//
//  Created by oceans on 2018/8/30.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "SearchListViewController.h"
#import "SearchListCollectionViewCell.h"
#import "SchoolListTableViewCell.h"
#import "TeacherListTableViewCell.h"
#import "ClassListTableViewCell.h"
#import "SchoolListModel.h"
#import "TeacherModel.h"
#import "ClassModel.h"
#import "NormalWebViewController.h"
#import "TeacherDetailViewController.h"
#import "HttpRequest.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "ClassListTableFooterView.h"
#import "SendRequestViewController.h"
#import "SearchHeaderReusableView.h"
#import "LoginViewController.h"

@interface SearchListViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, ClassListTableFooterViewDelegate, SearchHeaderReusableViewDelegate>

@property (strong, nonatomic) UICollectionView *collection;
@property (strong, nonatomic) NSMutableArray <NSString *> *historyArr;
@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) UITextField *textfield;
@property (strong, nonatomic) MetaModel *model;
@property (copy, nonatomic) NSString *className;

@property (strong, nonatomic) NSArray <ClassModel*> *recommendsArr;
@end

@implementation SearchListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.dataArr = [NSMutableArray array];
    [self loadHistory];
    [self setupView];
    [self loadRecommends];
}

- (void)loadRecommends {
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kget_class_rec paras:nil showProgress:NO successful:^(id  _Nullable result) {
        
        NSArray *array = result[@"data"][@"items"];
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:array.count];
        for (NSDictionary *dic in array) {
            ClassModel *model = [[ClassModel alloc] initWithDic:dic];
            [models addObject:model];
        }
        weakself.recommendsArr = models;
        if (weakself.collection.hidden == YES) {
            [weakself.tableview reloadData];
        }
    } failed:nil];
}

- (void)loadHistory {
    
    if ([_className isEqualToString:searchClassSchool]) {
        [self loadSchoolHistory];
    }else if ([_className isEqualToString:searchClassTeacher]) {
        [self loadTeacherHistory];
    }else if ([_className isEqualToString:searchClassClass]) {
        [self loadClassHistory];
    }
}

- (void)loadSchoolHistory {
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"search_history_school"];
    if (array == nil) {
        self.historyArr = [NSMutableArray array];
    }else {
        self.historyArr = [NSMutableArray arrayWithArray:array];
    }
}

- (void)loadTeacherHistory {
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"search_history_teacher"];
    if (array == nil) {
        self.historyArr = [NSMutableArray array];
    }else {
        self.historyArr = [NSMutableArray arrayWithArray:array];
    }
}

- (void)loadClassHistory {
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"search_history_class"];
    if (array == nil) {
        self.historyArr = [NSMutableArray array];
    }else {
        self.historyArr = [NSMutableArray arrayWithArray:array];
    }
}

- (void)saveHistory {
    
    if ([_className isEqualToString:searchClassSchool]) {
        [[NSUserDefaults standardUserDefaults] setObject:_historyArr forKey:@"search_history_school"];
    }else if ([_className isEqualToString:searchClassTeacher]) {
        [[NSUserDefaults standardUserDefaults] setObject:_historyArr forKey:@"search_history_teacher"];
    }else if ([_className isEqualToString:searchClassClass]) {
        [[NSUserDefaults standardUserDefaults] setObject:_historyArr forKey:@"search_history_class"];
    }
}

- (void)clearHistory {
    if ([_className isEqualToString:searchClassSchool]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"search_history_school"];
    }else if ([_className isEqualToString:searchClassTeacher]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"search_history_teacher"];
    }else if ([_className isEqualToString:searchClassClass]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"search_history_class"];
    }
    [_historyArr removeAllObjects];
    [_collection reloadData];
}

- (void)loadData {
    
    [self.dataArr removeAllObjects];
    self.model = nil;
    [self.tableview.footer resetNoMoreData];
    [self.tableview reloadData];
    __weak typeof(self) weakself = self;
    NSString *url = nil;
    if ([_className isEqualToString:searchClassTeacher]) {
        url = kteacher_list;
    }else if ([_className isEqualToString:searchClassSchool]) {
        url = kschool_list;
    }else {
        url = kget_class_search;
    }
    
    [HttpRequest getURL:url paras:@{@"name": _textfield.text} showProgress:NO successful:^(id  _Nullable result) {
        
        NSLog(@"%@", result);
        NSDictionary *dic = result[@"data"];
        
        NSArray *array = dic[@"items"];
        for (NSDictionary *ldic in array) {
            if ([weakself.className isEqualToString:searchClassSchool]) {
                SchoolListModel *model = [[SchoolListModel alloc] initWithDic:ldic];
                [weakself.dataArr addObject:model];
            }else if ([weakself.className isEqualToString:searchClassTeacher]) {
                TeacherModel *model = [[TeacherModel alloc] initWithDic:ldic];
                [weakself.dataArr addObject:model];
            }else {
                ClassModel *model = [[ClassModel alloc] initWithDic:ldic];
                [weakself.dataArr addObject:model];
            }
        }
        
        [weakself.tableview reloadData];
        MetaModel *model = [[MetaModel alloc] initWithDic:[dic objectForKey:@"meta"]];
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            [weakself.tableview.footer endRefreshingWithNoMoreData];
        }else {
            weakself.model = model;
        }
    } failed:nil];
}

- (void)loadMoreData {
    
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 12 - 42, 34)];
    field.borderStyle = UITextBorderStyleRoundedRect;
    field.delegate = self;
    field.backgroundColor = COLOR(238, 238, 238, 1);
    self.textfield = field;
    self.navigationItem.titleView = field;
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(forBack)];
    [right setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0], NSForegroundColorAttributeName: [UIColor colorWithRed:149/255.0 green:149/255.0 blue:149/255.0 alpha:1.0]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenWidth - XNavigationHeight) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerNib:[UINib nibWithNibName:@"SearchListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SearchListCollectionViewCell"];
    [_collection registerNib:[UINib nibWithNibName:@"SearchHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchHeaderReusableView"];
    [self.view addSubview:_collection];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight - XNavigationHeight) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorInset = UIEdgeInsetsMake(0, 16, 0, 0);
        _tableview.footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [_tableview registerNib:[UINib nibWithNibName:_className bundle:nil] forCellReuseIdentifier:_className];
        [_tableview registerClass:[ClassListTableFooterView class] forHeaderFooterViewReuseIdentifier:@"ClassListTableFooterView"];
        _tableview.tableFooterView = [UIView new];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

#pragma mark - uitableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if ([_className isEqualToString:searchClassClass] && _dataArr.count == 0) {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0 && _dataArr.count == 0) {
        return 0.868 * ScreenWidth;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0 && _dataArr.count == 0) {
        ClassListTableFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ClassListTableFooterView"];
        view.delegate = self;
        return view;
    }
    return nil;
}

- (void)footerViewSendButtonPressed {
    if ([UserModel shared].hasLogin == YES) {
        SendRequestViewController *con = [[SendRequestViewController alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:con];
        [self presentViewController:navi animated:YES completion:nil];
    }else {
        UINavigationController *controller = [LoginViewController loginViewController];
        [self presentViewController:controller animated:YES completion:nil];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return _dataArr.count;
    }
    return _recommendsArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([_className isEqualToString:searchClassClass]) {
        const CGFloat height = (ScreenWidth - 20.0) * 0.39 * 0.586 + 32;
        return height;
    }else {
        return 95.0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([_className isEqualToString:searchClassSchool]) {
        SchoolListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_className];
        return cell;
    }else if ([_className isEqualToString:searchClassTeacher]) {
        TeacherListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_className];
        return cell;
    }else {
        ClassListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_className];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([_className isEqualToString:searchClassSchool]) {
        SchoolListTableViewCell *scell = (SchoolListTableViewCell*)cell;
        SchoolListModel *model = _dataArr[indexPath.row];
        [scell.schoolImageView sd_setImageWithURL:[NSURL URLWithString:model.cover]];
        scell.nameLabel.text = model.name;
        scell.addressLabel.text = [NSString stringWithFormat:@"%@%@", model.region, model.address_detail];
        scell.starView.value = model.grade;
    }else if ([_className isEqualToString:searchClassTeacher]) {
        TeacherListTableViewCell *tcell = (TeacherListTableViewCell*)cell;
        TeacherModel *model = _dataArr[indexPath.row];
        [tcell.teacherImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
        tcell.nameLabel.text = model.name;
        if (model.gender == 0) {
            tcell.genderImageView.image = nil;
        }else if (model.gender == 1) {
            tcell.genderImageView.image = [UIImage imageNamed:@"gender_m"];
        }else {
            tcell.genderImageView.image = [UIImage imageNamed:@"gender_f"];
        }
        tcell.starView.value = model.grade;
    }else {
        ClassListTableViewCell *ccell = (ClassListTableViewCell *)cell;
        ClassModel *model = nil;
        if (indexPath.section == 0) {
            model = _dataArr[indexPath.row];
        }else {
            model = _recommendsArr[indexPath.row];
        }
        [ccell.classImageView sd_setImageWithURL:[NSURL URLWithString:model.thumb]];
        ccell.titleLabel.text = model.name;
        ccell.teacherLabel.text = model.teacher;
        ccell.timeLabel.text = model.begintime;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"￥ " attributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:1.0 green:0 blue:54/255.0 alpha:1.0], NSFontAttributeName: [UIFont systemFontOfSize:10.0]}];
        NSAttributedString *price = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f", model.price] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]}];
        [string appendAttributedString:price];
        ccell.priceLabel.attributedText = string;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([_className isEqualToString:searchClassSchool]) {
        SchoolListModel *model = _dataArr[indexPath.row];
        NormalWebViewController *controller = [[NormalWebViewController alloc] init];
        controller.url = model.link;
        [self.navigationController pushViewController:controller animated:YES];
    }else if ([_className isEqualToString:searchClassTeacher]) {
        TeacherDetailViewController *detail = [[TeacherDetailViewController alloc] init];
        detail.teacher = _dataArr[indexPath.row];
        [self.navigationController pushViewController:detail animated:YES];
    }else {
        ClassModel *model = _dataArr[indexPath.row];
        NormalWebViewController *controller = [[NormalWebViewController alloc] init];
        controller.url = model.link;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

#pragma mark - uicollectionview

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(ScreenWidth, 45);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SearchHeaderReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchHeaderReusableView" forIndexPath:indexPath];
        view.delegate = self;
        return view;
    }
    return nil;
}

- (void)deleteSearchHistory {
    [self clearHistory];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _historyArr.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGRect rect = [_historyArr[indexPath.item] boundingRectWithSize:CGSizeMake(100, 17.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13.0]} context:nil];
    return CGSizeMake(rect.size.width + 20, 27);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchListCollectionViewCell" forIndexPath:indexPath];
    cell.textLabel.text = _historyArr[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.textfield.text = _historyArr[indexPath.item];
    [self.textfield resignFirstResponder];
    self.collection.hidden = YES;
    [self loadData];
    if (indexPath.item != 0) {
        NSString *string = _historyArr[indexPath.item];
        [_historyArr removeObjectAtIndex:indexPath.item];
        [_historyArr insertObject:string atIndex:0];
        [self saveHistory];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    NSString *string = textField.text;
    if ([_historyArr containsObject:string]) {
        
        [_historyArr removeObject:string];
        [_historyArr insertObject:string atIndex:0];
    }else {
        [_historyArr insertObject:string atIndex:0];
    }
    [self.textfield resignFirstResponder];
    self.collection.hidden = YES;
    [self loadData];
    [self saveHistory];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    _collection.hidden = NO;
    [_collection reloadData];
    
    return YES;
}

+ (UINavigationController *)searchController:(NSString *)name {
    
    SearchListViewController *controller = [[SearchListViewController alloc] init];
    controller.className = name;
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
    return navi;
}

- (void)forBack {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
